const sqlModule = require('../../common/database/sql');

const models = sqlModule.models;

const usersModel = models.users;

function list(param) {
  return new Promise(async (resolve, reject) => {
    try {
      const query = {
        filter: {
          where: {
            roles: {
              $in: param.roles
            }
          }
        },
        pageSize: param.pageSize,
        pageNumber: param.pageNum,
        getCount: true
      };
      if (param.type !== '全部' && param.type) {
        query.filter.where.teacherType = {
          $in: [param.type]
        };
      }
      const todos = await usersModel.list(query);
      resolve(todos.data);
    } catch (error) {
      reject(error);
    };
  })
}
//修改用户的当前身份
function edit(param) {
  return new Promise(async (resolve, reject) => {
    try {
      const query = {
        data: {},
        filter: {
          where: {
            _id: {
              $eq: param._id
            }
          }
        }
      };
      if (param.role) {
        query.data.role = param.role;
      }
      const result = await usersModel.update(query)
      if (result.data.count >= 1) {
        resolve(true);
      } else {
        resolve(false);
      }
    } catch (error) {
      reject(error);
    };
  })
}
//查询用户详情
function byId(id) {
  return new Promise(async (resolve, reject) => {
    try {
      const query = {
        filter: {
          where: {
            _id: {
              $eq: id
            }
          }
        }
      };
      const todo = await usersModel.get(query);
      resolve(todo.data);
    } catch (error) {
      reject(error);
    };
  })
}
//查询用户详情
function byOpenid(id) {
  return new Promise(async (resolve, reject) => {
    try {
      const query = {
        filter: {
          where: {
            openid: {
              $eq: id
            }
          }
        },
        select: {
          $master: true,
          "class": true // 关联信息
        },
      };
      const todo = await usersModel.get(query);
      resolve(todo.data);
    } catch (error) {
      reject(error);
    };
  })
}

function add(user) {
  return new Promise(async (resolve, reject) => {
    try {
      const query = {
        data: {
          ...user
        }
      };
      const result = await usersModel.create(query)
      resolve(result.data);
    } catch (error) {
      reject(error);
    };
  })
}



module.exports = {
  list,
  edit,
  byId,
  byOpenid,
  add
}